<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            margin: 0;
        }
        .box {
            width: 200px;
            height: 200px;
            background-color: red;
            border-radius: 50%;
        }
    </style>
</head>
<body>
    <!-- <div class="box"></div> -->
    <img class="box" src="" alt="">
    <!-- img -->

    <script src="../../工具函数/范围取值.js"></script>
    <script>

        const box = document.querySelector('.box');

        let innerX = 0;
        let innerY = 0;

        /**
         * @param { Event } e
        */
        function onMouseMove(e) {
            // console.log(e.clientX, e.clientY);
            // left, top 会引起页面元素的重排
            // box.setAttribute('style', `left: ${ e.clientX }px; top: ${ e.clientY }px;`);
            // css3 只重绘 不重排 (性能优化)
            const x = e.clientX - innerX;
            const y = e.clientY - innerY;
            const vh = window.innerHeight; // 800多
            const vw = window.innerWidth;
            const boxH = box.height;
            const boxW = box.width;

            const maxY = vh - boxH;
            const maxX = vw - boxW;

            // 真实的y
            const realY = getRangeValue(y, [0, maxY]);
            const realX = getRangeValue(x, [0, maxX]);

            box.setAttribute('style', `transform: translate(${ realX }px, ${ realY }px);`);
        }

        // 鼠标按下
        box.addEventListener('mousedown', function (e) {
            e.preventDefault();
            innerX = e.offsetX;
            innerY = e.offsetY;
            document.addEventListener('mousemove', onMouseMove);
        });

        // 鼠标抬起
        box.addEventListener('mouseup', function () {
            document.removeEventListener('mousemove', onMouseMove);
        });

    </script>
</body>
</html>